package com.xmkj.bearuser.my;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.common.Entity.ShareEntity;
import com.common.Entity.UserEntity;
import com.common.base.Config;
import com.common.cons.Constans;
import com.common.mvp.BaseMvpFragment;
import com.common.mvp.BasePresenter;
import com.common.retrofit.method.GetShareDatasMethods;
import com.common.retrofit.method.GetUserInfoMethods;
import com.common.retrofit.method.ShareSuccessMethods;
import com.common.retrofit.subscriber.CommonSubscriber;
import com.common.retrofit.subscriber.SubscriberListener;
import com.common.rxbus.RxBus;
import com.common.rxbus.postevent.RxKeyEvent;
import com.common.utils.EmptyUtils;
import com.common.utils.GlideCircleTransform;
import com.common.utils.LogUtils;
import com.common.utils.SPUtils;
import com.common.widget.imageview.image.ImageLoaderUtils;
import com.common.widget.itemview.BaseItemLayout;
import com.common.widget.itemview.config.ConfigAttrs;
import com.common.widget.itemview.config.Mode;
import com.xmkj.payandlogin.ShareConfig;
import com.xmkj.payandlogin.ShareManager;
import com.xmkj.payandlogin.ShareUtil;
import com.xmkj.payandlogin.share.ShareListener;
import com.xmkj.payandlogin.share.SharePlatform;
import com.xmkj.bearuser.R;
import com.xmkj.bearuser.count.LoginActivtiy;
import com.xmkj.bearuser.mine.activity.ChongZhiActivity;
import com.xmkj.bearuser.mine.activity.InfoCompileActivity;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.functions.Action1;

/**
 * Create by leo
 * 创建日期：2018/5/3
 * 描述：
 */

public class MyFragment extends BaseMvpFragment {
    @BindView(R.id.iv_face)
    ImageView ivFace;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.iv_setting)
    ImageView ivSetting;
    @BindView(R.id.tv_gold)
    TextView tvGold;
    @BindView(R.id.tv_chongzhi)
    TextView tvChongzhi;
    @BindView(R.id.layout_mine)
    BaseItemLayout mLayoutMine;
    private ConfigAttrs attrs;
    private UserEntity entity;


    @Override
    protected BasePresenter createPresenterInstance() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void onViewCreated(View view) {
        ivFace = view.findViewById(R.id.iv_face);
        tvName = view.findViewById(R.id.tv_name);
        ivSetting = view.findViewById(R.id.iv_setting);
        tvGold = view.findViewById(R.id.tv_gold);
        tvChongzhi = view.findViewById(R.id.tv_chongzhi);
        mLayoutMine = view.findViewById(R.id.layout_mine);
    }

    @Override
    protected void doLogicFunc() {
        ShareConfig config = ShareConfig.instance()
                .qqId(Config.APP_QQ_ID)
                .wxSecret(Config.APP_SERECET)
                .wxId(Config.APP_ID);
        ShareManager.init(config);
        rxManager.add(RxBus.getDefault().toObservable(RxKeyEvent.class).subscribe(new Action1<RxKeyEvent>() {
            @Override
            public void call(RxKeyEvent rxKeyEvent) {
                if (EmptyUtils.isNotEventEmpty(rxKeyEvent, RxKeyEvent.MODIFYSUCCESS) && (Boolean) rxKeyEvent.getValue()) {
                    getUserInfo();
                }
            }
        }));
        setMineItemView();
        attachClickListener(ivSetting);
        attachClickListener(tvChongzhi);
        attachClickListener(ivFace);
        getUserInfo();

    }

    private void getUserInfo() {
        CommonSubscriber<UserEntity> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {

                dismissProgressDialog();
                entity = (UserEntity) o;

                tvName.setText(entity.nickname);
                tvGold.setText("金币："+ entity.account+"个");
                if(EmptyUtils.isNotEmpty(entity.face)){
                    ImageLoaderUtils.displayCircle(ivFace, entity.face);

                }else {
                    ivFace.setBackgroundResource(R.mipmap.myperson);
                }
//                gotoHttpRep();
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
 /*               swipRefresh.setRefreshing(false);*/


                RequestOptions options = new RequestOptions()
                        .centerCrop()
                        .error(R.mipmap.myperson)
                        .placeholder(R.mipmap.myperson)
                        .priority(Priority.HIGH)
                        .transform(new GlideCircleTransform());
//        调用glide显示图片：
                Glide.with(context).load("").apply(options).into(ivFace);
                showToastMsg(e);
            }
        });
        uid = SPUtils.getShareInt(Constans.UID);
        hashid =  SPUtils.getShareString(Constans.HASHID);
        GetUserInfoMethods.getInstance().userDetail(subscriber, uid, hashid);
        rxManager.add(subscriber);
    }

    @Override
    protected void onViewClicked(View view) {
        if(EmptyUtils.isEmpty(SPUtils.getShareString(Constans.HASHID))){
            gotoActivity(LoginActivtiy.class);
            return;
        }
        if(view.getId()==ivSetting.getId()){
         gotoActivity(InfoCompileActivity.class);
        }else if(view.getId()==tvChongzhi.getId()){
            gotoActivity(ChongZhiActivity.class);
        }else if(view.getId()==ivFace.getId()){
            gotoActivity(InfoCompileActivity.class);
        }
    }

    private void setMineItemView() {
        if (EmptyUtils.isNotEmpty(mLayoutMine) && mLayoutMine.getChildCount() > 0) {
            mLayoutMine.removeAllViews();
            mLayoutMine.getViewList().clear();
        }
        List<String> valueList = new ArrayList<>();
        List<Integer> resIdList = new ArrayList<>();
        valueList.add("中奖纪录");
        valueList.add("我的积分");
        valueList.add("我的晒单");
        valueList.add("充值记录");
        valueList.add("收货地址");
        valueList.add("每日活动");
        valueList.add("客服");


        attrs = new ConfigAttrs();
        attrs.setValueList(valueList)  // 文字 list
                .setResIdList(resIdList) // icon list
                .setIconWidth(25)  //设置icon 的大小
                .setIconHeight(25)
                .setItemMode(Mode.TEXT)
                .setItemMarginTop(1)
                .setArrowResId(R.mipmap.next)
                .setMarginRight(12);
        mLayoutMine.setConfigAttrs(attrs).create();
        mLayoutMine.setOnBaseItemClick(new BaseItemLayout.OnBaseItemClick() {
            @Override
            public void onItemClick(int position) {
                if(EmptyUtils.isEmpty(SPUtils.getShareString(Constans.HASHID))){
                    gotoActivity(LoginActivtiy.class);
                    return;
                }
                switch (position) {
                    case 0:/*  // 中奖记录
                        Intent intent = new Intent(context,MyWalletActivity.class);
                        intent.putExtra(Constans.INFOBEAN,infoBean);
                        startActivity(intent);*/
                        gotoActivity(ZhongJiangRecordAcitvity.class);
                        break;
                    case 1:
                        gotoActivity(MyJiFenActivity.class);
//                        return;
//                        gotoActivity(ApplyForBillActivity.class);
                        break;
                    case 2:
//                        gotoActivity(WashCarRecordActivity.class);
                        // 我的晒单
                        gotoActivity(MyShareOrderActivity.class);
//                        Intent intent2 = new Intent(context, BaseUrlActivity.class);
//                        intent2.putExtra(BaseUrlActivity.MAIN_URL, mineBean.kefu);
//                        intent2.putExtra(BaseUrlActivity.TITILE, "服务中心");
//                        context.startActivity(intent2);
////
//                        Intent surlIntent = new Intent(context, BaseUrlActivity.class);
//                        surlIntent.putExtra(BaseUrlActivity.MAIN_URL,mineBean.kefu);
//                        startActivity(surlIntent);
                        break;
                    case 3:
//                        gotoActivity(MyCardActivity.class);
                        gotoActivity(ChongZhiRecordsActivity.class);
//                        Intent intent3 = new Intent(context, BaseUrlActivity.class);
//                        intent3.putExtra(BaseUrlActivity.MAIN_URL, mineBean.cjwt);
//                        intent3.putExtra(BaseUrlActivity.TITILE, "常见问题");
//                        context.startActivity(intent3);
                        break;
                    case 4:
                        //收货地址
//                        gotoActivity(FaPiaoApplyActivity.class);
                        gotoActivity(AddressListActivity.class);
                        break;
                    case 5:
                        //信用额度
//                        gotoActivity(CriditLimitActivity.class);
//                        gotoActivity(SettingActivity.class);
                        getShareData();
                        break;
                    case  6 :


                        AndPermission.with(MyFragment.this)
                                .requestCode(105)
                                .permission(Manifest.permission.CALL_PHONE)
                                .rationale(mRationaleListener)
                                .send();
                        break;

                }
            }
        });
    }

    //申请权限
    private RationaleListener mRationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
            new AlertDialog.Builder(context)
                    .setTitle("友好提醒")
                    .setMessage("没有权限您不能拨打电话，请把权限赐给我吧!(如果设置不再提示,您可以在设置中打开权限)")
                    .setPositiveButton("好，给你", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.resume();// 用户同意继续申请。
                        }
                    })
                    .setNegativeButton("我拒绝", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.cancel(); // 用户拒绝申请。
                        }
                    }).show();
        }
    };
    @PermissionYes(105)
    private void openPic() {
        LogUtils.e("成功回调了-->");
        if(EmptyUtils.isNotEmpty(entity)&&EmptyUtils.isNotEmpty(entity.kefu_list)&&entity.kefu_list.size()>0){
            gotoCall(entity.kefu_list.get(0));


        }


    }
    private void getShareData() {
        CommonSubscriber<ShareEntity> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();
                ShareEntity    shareEntity = (ShareEntity) o;
                if(EmptyUtils.isNotEmpty(shareEntity)){
                    gotoShare(shareEntity);
                }
//                gotoHttpRep();
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });
        GetShareDatasMethods.getInstance().share(subscriber, SPUtils.getShareInt(Constans.UID),SPUtils.getShareString(Constans.HASHID));
        rxManager.add(subscriber);
    }
    @Override
    protected void setStatusBar() {

    }
    private void gotoShare(final ShareEntity shareEntity) {
        showShareButton();
        setOnShareClick(new OnShareClick() {
            @Override
            public void wechat() {
                if (ShareUtil.isInstalled(SharePlatform.WX, context)) {

//                    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon);
//                    if (EmptyUtils.isEmpty(mineBean.img)) {
//                        ShareUtil.shareMedia(context, SharePlatform.WX, mineBean.title, mineBean.content, mineBean.url, bitmap, shareListener);
//
//                    } else {
//                        ShareUtil.shareMedia(context, SharePlatform.WX, mineBean.title, mineBean.content, mineBean.url, mineBean.img, shareListener);
                    ShareUtil.shareMedia(context, SharePlatform.WX, shareEntity.share_title.equals("") ? "拼夺宝" : shareEntity.share_title, shareEntity.share_content, shareEntity.share_url, shareEntity.logo, shareListener);
//                    }

                } else {
                    showToastMsg("未安装微信");
                }
            }

            @Override
            public void wethatCircle() {
                if (ShareUtil.isInstalled(SharePlatform.WX_TIMELINE, context)) {
//                    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon);
//                    if (EmptyUtils.isEmpty(mineBean.img)) {
//                        ShareUtil.shareMedia(context, SharePlatform.WX_TIMELINE, mineBean.title, mineBean.content, mineBean.url, bitmap, shareListener);
//
//                    } else {
//                        ShareUtil.shareMedia(context, SharePlatform.WX_TIMELINE, mineBean.title, mineBean.content, mineBean.url, mineBean.img, shareListener);

                    ShareUtil.shareMedia(context, SharePlatform.WX_TIMELINE, shareEntity.share_title.equals("") ? "拼夺宝" : shareEntity.share_title, shareEntity.share_content, shareEntity.share_url, shareEntity.logo, shareListener);
//                    }
                } else {
                    showToastMsg("未安装微信");
                }
            }

            @Override
            public void qq() {
                if (ShareUtil.isInstalled(SharePlatform.QQ, context)) {
//                    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon);
               /*     if (EmptyUtils.isEmpty(mineBean.img)) {
                        ShareUtil.shareMedia(context, SharePlatform.QQ, mineBean.title, mineBean.content, mineBean.url, bitmap, shareListener);

                    } else {*/
//                        ShareUtil.shareMedia(context, SharePlatform.QQ, mineBean.title, mineBean.content, mineBean.url, mineBean.img, shareListener);
                    ShareUtil.shareMedia(context, SharePlatform.QQ, shareEntity.share_title.equals("") ? "拼夺宝" : shareEntity.share_title, shareEntity.share_content, shareEntity.share_url, shareEntity.logo, shareListener);

//                    }

                } else {
                    showToastMsg("未安装QQ");
                }
            }
        });
    }

    private ShareListener shareListener = new ShareListener() {
        @Override
        public void shareSuccess() {
            showToastMsg("分享成功");
            Sharesuccessfully();
        }

        @Override
        public void shareFailure(Exception e) {
            showToastMsg("分享失败");
        }

        @Override
        public void shareCancel() {
            showToastMsg("取消分享");
        }
    };
    private void Sharesuccessfully() {
        CommonSubscriber<Object> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();

//                gotoHttpRep();
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });
        ShareSuccessMethods.getInstance().shareSuccess(subscriber, SPUtils.getShareInt(Constans.UID),SPUtils.getShareString(Constans.HASHID));
        rxManager.add(subscriber);
    }

    private void gotoCall(final String phone) {
        if (EmptyUtils.isEmpty(phone)) {
            return;
        }
        showTwoDialog("提示", phone, "拨打", "取消");
        setOnDialogViewClick(new OnDialogViewClick() {
            @Override
            public void leftViewClick() {
//                        showToastMsg("hha");
                Intent intent = new Intent(); // 意图对象：动作 + 数据
                intent.setAction(Intent.ACTION_CALL); // 设置动作
                Uri data = Uri.parse("tel:" + phone); // 设置数据
                intent.setData(data);
                startActivity(intent); // 激活Activity组件
            }

            @Override
            public void singleViewClick() {

            }
        });


    }

    @PermissionNo(105)
    private void injectPic() {
        LogUtils.e("失败回调了-->");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        // 只需要调用这一句，剩下的 AndPermission 自动完成。
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }
}
